package stack.medium;

import java.util.Stack;

/**
 * 字符串解码
 * 示例 1：
 *
 * 输入：s = "3[a]2[bc]"
 * 输出："aaabcbc"
 * 示例 2：
 *
 * 输入：s = "3[a2[c]]"
 * 输出："accaccacc"
 * 示例 3：
 *
 * 输入：s = "2[abc]3[cd]ef"
 * 输出："abcabccdcdcdef"
 * 示例 4：
 *
 * 输入：s = "abc3[cd]xyz"
 * 输出："abccdcdcdxyz"
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/decode-string
 */
public class DecodeString_394 {

    public String decodeString(String s) {
        int multi = 0;
        Stack<Integer> integerStack = new Stack<>();
        Stack<String> stringStack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                multi = multi * 10 + (c - '0');
            } else if (c == '[') {
                integerStack.push(multi);
                multi = 0;
                stringStack.push(String.valueOf(c));
            } else if (c == ']') {
                StringBuilder sb = new StringBuilder();
                while (!stringStack.isEmpty() && !stringStack.peek().equals(String.valueOf('['))) {
                    sb.insert(0, stringStack.pop());
                }
                stringStack.pop();
                String s1 = sb.toString();
                Integer integerPop = integerStack.pop();
                while (integerPop-- > 1) {
                    sb.append(s1);
                }
                stringStack.push(sb.toString());
            } else {
                stringStack.push(String.valueOf(c));
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!stringStack.isEmpty()) {
            sb.insert(0, stringStack.pop());
        }
        return sb.toString();
    }
}
